package com.qingzhuge.sys.controller;


import com.google.gson.Gson;
import com.qingzhuge.common.HttpCode;
import com.qingzhuge.common.annotation.ASysLog;
import com.qingzhuge.common.enums.EAuthorityType;
import com.qingzhuge.common.enums.EResourceType;
import com.qingzhuge.common.validator.ValidatorUtil;
import com.qingzhuge.controller.BasePkLongController;
import com.qingzhuge.core.annotation.AResource;
import com.qingzhuge.dto.response.ResponseBodyDto;
import com.qingzhuge.exception.ServiceException;
import com.qingzhuge.file.service.cloud.FileStorageFactory;
import com.qingzhuge.sys.dto.request.SysConfigRequestDto;
import com.qingzhuge.sys.dto.request.SysSiteConfigRequestDto;
import com.qingzhuge.sys.dto.response.SysConfigResponseDto;
import com.qingzhuge.sys.dto.response.SysSiteConfigResponseDto;
import com.qingzhuge.sys.entity.SysConfig;
import com.qingzhuge.sys.entity.SysSiteConfig;
import com.qingzhuge.sys.service.ISysConfigService;
import com.qingzhuge.utils.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author : zero.xiao
 * @description : 系统配置信息
 * @date :2018/6/8 0008 下午 14:48
 * @modified :
 */
@ASysLog(value = "系统配置")
@Api(tags = "S系统配置")
@AResource(name = "系统配置", type = EResourceType.menu, catalog = "系统管理")
@RestController
@RequestMapping("api/sys/auth/config")
public class SysConfigController extends BasePkLongController<SysConfig, ISysConfigService, SysConfigRequestDto, SysConfigResponseDto> {
    @Resource
    private ISysConfigService sysConfigService;

    @Override
    public ResponseEntity<ResponseBodyDto<PageUtil<SysConfigResponseDto>>> queryPage(SysConfigRequestDto entity) {
        return super.queryPage(entity);
    }

    @Override
    public ResponseEntity<ResponseBodyDto<SysConfigResponseDto>> get(@PathVariable Long id) {
        return super.get(id);
    }

    @Override
    @AResource(type = EResourceType.button, authority = EAuthorityType.UPDATE)
    public ResponseEntity<ResponseBodyDto<SysConfigResponseDto>> save(@RequestBody SysConfigRequestDto config) {
        ValidatorUtil.validateEntity(config);
        return super.update(config);
    }

    /**
     * 修改配置
     */
    @Override
    public ResponseEntity<ResponseBodyDto<SysConfigResponseDto>> update(@RequestBody SysConfigRequestDto config) {
        ValidatorUtil.validateEntity(config);
        return super.update(config);
    }

    @ApiOperation(value = "系统配置信息")
    @GetMapping("/site")
    public ResponseEntity<ResponseBodyDto<SysSiteConfigResponseDto>> site() {
        SysSiteConfig config = sysConfigService.getConfigObject(SysSiteConfig.SYS_SITE_CONFIG_KEY, SysSiteConfig.class);
        SysSiteConfigResponseDto responseDto = sysConfigService.bean2Dto(config, SysSiteConfigResponseDto.class);
        return returnSuccess(responseDto);
    }

    @ApiOperation(value = "保存系统配置")
    @AResource(type = EResourceType.button, authority = EAuthorityType.UPDATE, name = "修改系统配置")
    @PutMapping("/site")
    @PreAuthorize("hasRole('ROOT') or hasAnyAuthority('SYSTEM','ADMIN') and hasAuthority('UPDATE')")
    public ResponseEntity<ResponseBodyDto<Object>> siteSave(@RequestBody SysSiteConfigRequestDto requestDto) {
        if (null == requestDto) {
            return returnFailed(HttpCode.VALIDATOR_FAILED);
        }
        //校验类型
        ValidatorUtil.validateEntity(requestDto);
        SysConfig sysConfig = sysConfigService.getValue(SysSiteConfig.SYS_SITE_CONFIG_KEY);
        if (null == sysConfig) {
            sysConfig = new SysConfig();
            sysConfig.setKey(SysSiteConfig.SYS_SITE_CONFIG_KEY);
        }
        SysSiteConfig config = requestDto.doForward(requestDto, SysSiteConfig.class);
        sysConfig.setValue(new Gson().toJson(config));
        sysConfigService.save(sysConfig);
        return returnSuccess();
    }

    @ApiOperation(value = "上传logo")
    @PostMapping("/logo")
    @AResource(name = "修改logo", type = EResourceType.button, authority = EAuthorityType.UPLOAD)
    @PreAuthorize("hasRole('ROOT') or hasAnyAuthority('SYSTEM','ADMIN') and hasAuthority('UPDATE')")
    public ResponseEntity<ResponseBodyDto<String>> upload(@RequestParam("file") MultipartFile file) throws java.lang.Exception {
        if (file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }
        //上传文件
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String url = Objects.requireNonNull(FileStorageFactory.buildLocal("./upload")).uploadSuffix(file.getBytes(), "logo", suffix);
        return returnSuccess(url);
    }
}
